const Service = require('egg').Service;

class AccessLogService extends Service {
  /**
   * 记录访问日志到数据库
   * @param {Object} logData - 日志数据
   */
  async create(logData) {
    const { ctx } = this;
    const result = await ctx.db.insert('access_logs', {
        method: logData.method,
        url: logData.url,
        query: logData.query ? JSON.stringify(logData.query) : null,
        body: logData.body ? JSON.stringify(logData.body) : null,
        ip: logData.ip,
        user_agent: logData.userAgent,
        response_status: logData.responseStatus,
        response_time: logData.responseTime,
    });
    
    return result;

  }
  
  /**
   * 查询访问日志列表
   * @param {Object} options - 查询选项
   */
  async list(options = {}) {
    const { ctx } = this;
    const { page = 1, pageSize = 20 } = options;
    const offset = (page - 1) * pageSize;
    
    const sql = `
      SELECT * FROM access_logs 
      ORDER BY created_at DESC 
      LIMIT ? OFFSET ?
    `;
    
    const logs = await ctx.db.query(sql, [pageSize, offset]);
    return logs;
  }
  
  /**
   * 根据ID获取单条访问日志
   * @param {Number} id - 日志ID
   */
  async findById(id) {
    const { ctx } = this;
    const log = await ctx.db.get('access_logs', { id });
    return log;
  }
}

module.exports = AccessLogService;